package com.google.googlemarket.fragement;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.google.googlemarket.AppDetailActivity;
import com.google.googlemarket.R;
import com.google.googlemarket.adapter.BannerAdapter;
import com.google.googlemarket.adapter.HomeAdapter;
import com.google.googlemarket.base.BaseFragment;
import com.google.googlemarket.bean.HomeBean;
import com.google.googlemarket.http.Urls;
import com.google.googlemarket.utils.JsonUtil;
import com.google.googlemarket.utils.Keys;
import com.google.googlemarket.utils.Logger;
import com.google.googlemarket.utils.UiUtils;
import com.google.googlemarket.view.LoadMoreListView;
import com.google.googlemarket.view.OnloadingMoreListener;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by MrGao on 2017/9/17.
 */

public class HomeFragment extends BaseFragment {

    public static final int TYPE_INIT_DATA=0;
    public static final int TYPE_INIT_LOADMORE=1;
    private static final int SWITCH_PAGE = 0;

    private LoadMoreListView mListView;
    private HomeAdapter homeAdapter;
    private ViewPager view_pager;
    private LinearLayout ll_dots;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SWITCH_PAGE:
                    switchPage();
                    break;
            }

        }
    };

    /**
     * 切换ViewPager的滚动条
     */
    private void switchPage() {
        view_pager.setCurrentItem(view_pager.getCurrentItem()+1);
        mHandler.removeMessages(SWITCH_PAGE);
        mHandler.sendEmptyMessageDelayed(SWITCH_PAGE,3000);
    }

    @Override
    public CharSequence getTitle() {
        return "首页";
    }

    @Override
    public void initView() {
        mListView = findView(R.id.list_view);
        homeAdapter = new HomeAdapter(null);
        mListView.setAdapter(homeAdapter);

        View headerView =  View.inflate(mContext, R.layout.header_view, null);
        view_pager = (ViewPager) headerView.findViewById(R.id.view_pager);
        ll_dots = (LinearLayout) headerView.findViewById(R.id.ll_dots);
        mListView.addHeaderView(headerView);
    }

    @Override
    public void initListener() {
        view_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                position = position % ll_dots.getChildCount();
                for (int i=0;i<ll_dots.getChildCount();i++){
                    ll_dots.getChildAt(i).setSelected(i==position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mListView.setOnLoadingMoreListener(new OnloadingMoreListener() {
            @Override
            public void onLoadingMore() {
                Logger.i("LoadMore","加载更多");
                requestAsyncTask(TYPE_INIT_LOADMORE);
            }

            @Override
            public void onClickRetry() {
                Logger.i("LoadMore","点击重试");
                requestAsyncTask(TYPE_INIT_LOADMORE);
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HomeBean.AppInfo appInfo = (HomeBean.AppInfo) parent.getItemAtPosition(position);
                Intent intent = new Intent(mContext,AppDetailActivity.class);
                intent.putExtra(Keys.PACKAGE_NAME,appInfo.packageName);
                startActivity(intent);

            }
        });
    }

    @Override
    public void initData() {
        requestAsyncTask(TYPE_INIT_DATA);
    }

    @Override
    public int getContentViewLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public View getContentView() {
        return null;
    }

    @Override
    protected Object doInBackground(int type) {
        HashMap<String, String> params = new HashMap<>();
        params.put("index",homeAdapter.getCount()+"");
        String json = NetUtils.getJson(Urls.HOME,params);
        Logger.i("http","HomeFragment json:"+json);
        return json;
    }
    int count =1;
    @Override
    protected void onPostExecute(int requestType,Object result) {
        Logger.i("http","requestType:"+requestType+",result:"+result);
        HomeBean homeBean = JsonUtil.json2Bean((String) result, HomeBean.class);
        ArrayList<HomeBean.AppInfo> datas=null;
        if (homeBean!=null){
            datas = homeBean.list;
            showBanner(homeBean.picture);
        }

        switch (requestType){
            case TYPE_INIT_DATA:
                if ( checkInitData(datas)){
                    homeAdapter.getDatas().addAll(datas);
                    homeAdapter.notifyDataSetChanged();
                }
                break;
            case TYPE_INIT_LOADMORE:
                mListView.onLoadMoreComplete();
                if (checkLoadMoreData(datas,mListView)){
                    homeAdapter.getDatas().addAll(datas);
                    homeAdapter.notifyDataSetChanged();
                }
                break;
        }
//        mStateLayout.showLoadingView();
       /* ArrayList<String> datas = null;

        switch (requestType){
            case TYPE_INIT_DATA:
                datas = new ArrayList<>();
                for (int i = 0;i<20;i++){
                    datas.add("跑步第"+i+"天");
                }
                if ( checkInitData(datas)){
                    homeAdapter.getDatas().addAll(datas);
                    homeAdapter.notifyDataSetChanged();
                }
                break;
            case TYPE_INIT_LOADMORE:
                if (count == 1){
                    datas = new ArrayList<>();
                    datas.add("我是多加载出来的数据");
                }else if(count == 2){
                    datas=null;
                }else if(count == 3){
                    datas = new ArrayList<String>();
                    datas.add("我是点击之后重试获取到的数据");
                }else if(count == 4){
                    datas = new ArrayList<String>();
                    datas.add("没有更多数据");
                }
                count++;
                Logger.i("LoadMore","count:"+count+"datas:"+datas);
                mListView.onLoadMoreComplete();
                if (checkLoadMoreData(datas,mListView)){
                    homeAdapter.getDatas().addAll(datas);
                    homeAdapter.notifyDataSetChanged();
                }
                break;
        }*/

    }

    /**
     * 显示轮播图
     * @param picture
     */
    private void showBanner(ArrayList<String> picture) {
        if (picture==null){
            return;
        }

        //ViewPager下面的图片指示器
        for (int i=0;i<picture.size();i++){
            Logger.i("ll_dot",i);
            View dot = new View(mContext);
            dot.setBackgroundResource(R.drawable.selector_dot);
            int size = UiUtils.dpd2x(6);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size, size);
            layoutParams.leftMargin = i == 0 ? 0 : size;
            dot.setLayoutParams(layoutParams);
            ll_dots.addView(dot);
        }
        ll_dots.getChildAt(0).setSelected(true);
        view_pager.setAdapter(new BannerAdapter(picture));
        view_pager.setCurrentItem(view_pager.getAdapter().getCount()/2);
        mHandler.sendEmptyMessageDelayed(SWITCH_PAGE,3000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }
}
